import { EntityTarget, ObjectLiteral, DataSource, Repository, EntityManager, QueryRunner, SelectQueryBuilder } from "typeorm";
import config from '@/config'
import { Service } from 'typedi'

@Service()
export class Entity {
    // 使用 存储库 查询
    get<T extends ObjectLiteral>(entity: EntityTarget<T>): Repository<T> {
        return (<DataSource><unknown>config.orm).getRepository(entity)
    }

    // 基于 实体管理器 创建 QueryBuilder
    manager<T extends ObjectLiteral>(entity: EntityTarget<T> | any): SelectQueryBuilder<T> {
        return (<DataSource><unknown>config.orm).manager.createQueryBuilder(entity,entity.name.toLowerCase())
    }

    // 基于 数据源 创建 QueryBuilder
    source(queryRunner?: QueryRunner): SelectQueryBuilder<any> {
        return (<DataSource><unknown>config.orm).createQueryBuilder(queryRunner)
    }

    // 基于 存储库 使用  QueryBuilder
    repository<T extends ObjectLiteral>(entity: EntityTarget<T> | any): SelectQueryBuilder<ObjectLiteral> {
       return (<DataSource><unknown>config.orm).getRepository(entity).createQueryBuilder(entity.name.toLowerCase())
    }
}
